package com.maikang.exammall.task.async;

import com.maikang.exammall.repository.HospitalRepository;
import com.maikang.exammall.repository.PackageRepository;
import lombok.RequiredArgsConstructor;
import lombok.extern.log4j.Log4j2;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;

import java.util.Map;

@Component
@RequiredArgsConstructor
@Log4j2
public class PackageAsyncTask {
    private final PackageRepository packageRepository;
    private final HospitalRepository hospitalRepository;

    @Async("threadPoolTaskExecutor")
    @Transactional(rollbackFor = Exception.class)
    public void incrementPackageOrderCount(Iterable<Long> pkgIds) {
        packageRepository.incrementOrderCountByIds(pkgIds);
    }

    @Async("threadPoolTaskExecutor")
    @Transactional(rollbackFor = Exception.class)
    public void incrementPackageSoldCount(Map<Long, Integer> pkgIdCountMap) {
        for (Map.Entry<Long, Integer> entry: pkgIdCountMap.entrySet()) {
            packageRepository.incrementSoldCountById(entry.getKey(), entry.getValue());
        }
    }

    @Async("threadPoolTaskExecutor")
    @Transactional(rollbackFor = Exception.class)
    public void incrementHospitalOrderCount(Iterable<Long> hospitalIds) {
        hospitalRepository.incrementOrderCountByIds(hospitalIds);
    }
}
